package org.example;

import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

public class HttpServerApp {
    public static void main(String[] args) throws IOException {
        // 创建HTTP服务器，绑定到8080端口
        int port = 8080;
        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);

        // 注册根路径的处理器
        server.createContext("/", exchange -> {
            // 设置响应内容类型
            exchange.getResponseHeaders().set("Content-Type", "text/html; charset=UTF-8");

            // 响应内容
            String response = "<h1>Hello and welcome!</h1>";
            exchange.sendResponseHeaders(200, response.getBytes().length);

            // 发送响应
            try (OutputStream os = exchange.getResponseBody()) {
                os.write(response.getBytes());
            }
        });

        // 启动服务器
        server.start();
        System.out.println("服务器已启动，正在监听 " + port + " 端口...");
        System.out.println("请访问: http://localhost:" + port);
    }
}
